import { saveInstructReceipt } from '@/services/api/api-instruct-receipt';
import { SendOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormInstance, ProFormTextArea } from '@ant-design/pro-components';
import { Button, message } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import { useRef, useState } from 'react';
import { useAccess, useModel } from 'umi';
import UploadDragger from '../components/UploadDragger';

interface AddReceiptProps {
  recordId: string | undefined;
  onSave: () => void;
}

const AddReceipt: React.FC<AddReceiptProps> = ({ recordId, onSave }) => {
  const { initialState } = useModel('@@initialState');
  const access = useAccess();
  const formRef = useRef<ProFormInstance>();

  const [isUpload, setIsUploadState] = useState<boolean>(false);

  return (
    <DrawerForm
      title="填写回执"
      trigger={
        <Button
          icon={<SendOutlined />}
          type="primary"
          style={{
            background: '#87d068',
          }}
        >
          回执
        </Button>
      }
      layout="horizontal"
      formRef={formRef}
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        maskClosable: false,
        width: 800,
      }}
      initialValues={{
        assignType: '4',
      }}
      onFinish={async (values) => {
        if (isUpload) {
          message.warning('附件正在上传，请稍后再试！');
          return;
        }

        if (
          values.content === undefined ||
          values.content.length === 0 ||
          values.content.trim() === ''
        ) {
          message.warning('请输入回执内容');
          return;
        }

        if (values.attachments !== undefined && values.attachments.length > 0) {
          const attachments = values.attachments
            .filter((item: { status: string }) => {
              return item.status === 'done';
            })
            .map((item: { response: { data: { id: any } } }) => {
              return item.response.data.id;
            });

          values.attachments = attachments;
        }

        const response = await saveInstructReceipt({ recordId, ...values });
        if (response.code === 0) {
          message.success('提交成功');
          onSave();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProFormTextArea
        name="content"
        required
        label=""
        placeholder="请输入回执"
        fieldProps={{
          rows: 10,
          count: {
            show: true,
          },
        }}
      />

      <FormItem name="attachments">
        <UploadDragger
          onPreview={(file) => {}}
          access={{
            isPicture: true,
            isVideo: true,
            isOffice: true,
            isOther: true,
          }}
          url="/instruct/attachment/save"
        />
      </FormItem>
    </DrawerForm>
  );
};

export default AddReceipt;
